import std.json;
import std.stdio;
import etc.c.curl;
import std.process;
import std.exception;
import std.file;
import std.regex;
import std.array;
import std.algorithm;

static this(){
	//curl_global_init(CURL_GLOBAL_ALL);
}

string[] urls(){ 
	JSONValue val = parseJSON(urls_json);
	JSONValue[] flights = val.array;
	writeln("flights " , flights.length);
	
	string[] ret;
	foreach( JSONValue f; flights ){
		if( f.object["from"].str=="IEV" || f.object["to"].str=="IEV" ){
			//writeln( f.object["from"].str, f.object["to"].str, " ",  f.object["url"].str);
			ret ~= "http://wizzair.com" ~ f.object["url"].str;
		}
	}

/*	
	writeln("ret.size ", ret.length, " ", ret);
	
	string urlData = shell(`curl http://www.4shared.com/dev/alive.jsp`);
	writeln("urlData ", urlData);
	
	getUrlCached("/tmp/urlcache", "http://www.4shared.com/dev/alive.jsp");
*/	
	return ret;
}

void precacheUrls(string cacheDir){
	foreach( u; urls() ){
		getUrlCached(cacheDir, u);
	}
}

class TimetableEl{
	string date;
	string departureTime;
	string departurePort;
	string arrivalTime;
	string arrivalPort;
	this(string html){
		date = valByRegex(html,	`<input type="radio" name="departDate1" value="([^"]+)"/>`);
		departureTime = valByRegex(html,	`<span class="flights_departuretime">([^<]+)</span>`);
		departurePort = valByRegex(html,	`<span class="flights_departureairport">([^<]+)</span>`);
		arrivalTime = valByRegex(html,	`<span class="flights_arrivaltime">([^<]+)</span>`);
		arrivalPort = valByRegex(html,	`<span class="flights_arrivalairport">([^<]+)</span>`);

//		string june = valByRegex(html, "(201106..)");
//		if( june!="NA" ){
//		  writeln(june);
//
//		//if( sameHead(date,"201106") ){
//		  writeln(toString());
//	 	}	
	}
	
	string toString(){
		return date~ "  "~kievTime() ~ "  "~departureTime~ " "~ departurePort~ "   "~ arrivalTime~ " "~ arrivalPort;
	}
	
	string kievTime(){
		if( departurePort=="Київ Жуляни" ){
			return departureTime;
		}
		if( arrivalPort=="Київ Жуляни" ){
			return arrivalTime;
		}
		//enforce(false,"not kiev "~date);
		assert(0,"not kiev "~date);
	}
}

void findTimetable(string cacheDir){
	string[] allTimes;
	foreach( u; urls() ){
		string html = getUrlCached(cacheDir, u);
		string htmlNoLines = replace(html,"\n"," ");
		foreach(m; match(htmlNoLines, regex(`<li class="flights_date">.*?</li>`)))
	    {
	        //writefln(m.hit);
	        allTimes ~= (new TimetableEl(m.hit)).toString();
	        //writeln("----------------");
	    }
	}
	
	sort(allTimes);
	
	string prev8;
	foreach( s; allTimes ){
		if( startsWith(s,"201105") ){
			if(s[0..8]!=prev8 ){
				writeln();
				prev8 = s[0..8];
			}
		    writeln(s);
	 	}
	}
	
}

string valByRegex(string text, string regexSelector){
	auto m = match(text, regex(regexSelector)).front;
	if( m.captures().length<1 ){
		return "NA";
	}
	return m.captures()[1];
}

/+

<li class="flights_date"><div>

                                    <input type="radio" name="departDate1" value="20110618"/>18/06/2011<input type="submit"/>
                                </div><div class="flights_daylist"><div class="flights_flight">
                    Рейс <span class="flights_flightnumber">WU 6261</span>, виліт:
                    <span class="flights_departuretime">06:10</span>
                                        <span class="flights_departureairport">Київ Жуляни</span>,
                    <span class="flights_departurecountry">Україна</span>, прибуття:
                    <span class="flights_arrivaltime">08:45</span>

                                        <span class="flights_arrivalairport">Анталія</span>,
                    <span class="flights_arrivalcountry">Туреччина</span>. Авіаквитки від 
                    <span class="flights_price">UAH 4657</span>.
                </div></div></li>

+/


string getUrlCached(string cacheDir, string url){
	enforce(isDir(cacheDir));
	string fname = cacheDir  ~ "/";
	foreach( char c; url ){
		if( c=='/' ){
			c = '_';
		}
		fname ~= c;
	}
	if( std.file.exists(fname) && std.file.isFile(fname) ){
		return cast(string)std.file.read(fname);
	}else{
		string urlData = shell(`curl "` ~ url ~ `"`);
		std.file.append(fname, urlData);
		return urlData;
	}
}

//string readUrl(){
//	CURL *curl;
//  CURLcode res;
// 
//  curl = curl_easy_init();
//  if(curl) {
//  	int CURLOPT_URL   =   10002;
//    curl_easy_setopt(curl, CURLOPT_URL, "http://www.4shared.com");
//    res = curl_easy_perform(curl);
// 
//    /* always cleanup */ 
//    curl_easy_cleanup(curl);
//  }
//  return "";
//}

string urls_json = import("wizzAirFlights.json");